<template>
    <view class="pb-safe-area">
        <view class="x-navbar x-navbar-sticky x-navbar-body" :style="[`--bg-opacity:${opacity.navbar}`, '--padding:0px', `padding-top:${PLATFORM.statusBarHeight}px`]">
            <view class="x-navbar-icons" @tap="$page.back()">
                <uni-icons type="left" size="24" color="var(--xl-primary-dark-3)"></uni-icons>
            </view>
            <view class="x-navbar-icons"></view>
            <view class="x-navbar-content" style="opacity: var(--bg-opacity);">
                <text class="text-primary h6 font-weight-700 text-ellipsis-1 x-navbar-title">服务详情</text>
            </view>
            <view class="x-navbar-icons"></view>
            <view class="x-navbar-icons"></view>
        </view>
        <view class="p-4 flex flex-column grid-gap-6">
            <view class="flex bg-white rounded-4 p-4 flex-x-space-between">
                <view class="flex flex-column flex-center grid-gap-2" :style="{ opacity: info.state >= 1 ? 1 : 0.5 }">
                    <image src="@/static/icons/order_accept.png" class="state-icon"></image>
                    <text class="state-text">{{ WebConfigStore.replaceIndustryPersonnelName('技师接单') }}</text>
                </view>
                <view class="flex flex-column flex-center grid-gap-2" :style="{ opacity: info.state >= 2 ? 1 : 0.5 }" v-if="!info.to_shop">
                    <image src="@/static/icons/order_go.png" class="state-icon"></image>
                    <text class="state-text">{{ WebConfigStore.replaceIndustryPersonnelName('技师出发') }}</text>
                </view>
                <view class="flex flex-column flex-center grid-gap-2" :style="{ opacity: info.state >= 3 ? 1 : 0.5 }" v-if="!info.to_shop">
                    <image src="@/static/icons/order_arrive.png" class="state-icon"></image>
                    <text class="state-text">{{ WebConfigStore.replaceIndustryPersonnelName('技师到达') }}</text>
                </view>
                <view class="flex flex-column flex-center grid-gap-2" :style="{ opacity: info.state >= 4 ? 1 : 0.5 }">
                    <image src="@/static/icons/order_start.png" class="state-icon"></image>
                    <text class="state-text">开始服务</text>
                </view>
                <view class="flex flex-column flex-center grid-gap-2" :style="{ opacity: info.state >= 10 ? 1 : 0.5 }">
                    <image src="@/static/icons/order_end.png" class="state-icon"></image>
                    <text class="state-text">服务完成</text>
                </view>
            </view>
            <view class="bg-white rounded-4 flex flex-column flex-center py-6" v-if="info.qrcode && info.state === 3">
                <image :src="info.qrcode" style="width: 200px;height: 200px;" />
                <text class="h9 text-placeholder">{{ WebConfigStore.replaceIndustryPersonnelName('技师核验二维码') }}</text>
            </view>
            <view class="flex flex-column bg-white rounded-4 p-4" v-if="info.state === 4 && info.verification">
                <view class="flex flex-column flex-center grid-gap-2">
                    <uni-icons type="checkbox-filled" size="64" color="var(--xl-primary)"></uni-icons>
                    <text class="font-weight-600 text-primary">核验成功</text>
                    <text class="h9 text-primary">{{ info.verification_time }}</text>
                </view>
                <view class="flex flex-column grid-gap-4 p-6">
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">预约时间</text>
                        <text class="flex-1 h10">{{ info.start_time }}</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">服务时长</text>
                        <text class="flex-1 h10">{{ info.duration }}分钟</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">计划通勤时长</text>
                        <text class="flex-1 h10">{{ info.commuting_duration }}分钟</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">计划抵达时间</text>
                        <text class="flex-1 h10">{{ info.plan_arrival_time }}</text>
                    </view>
                    <view class="flex" v-if="info.commuting_time">
                        <text class="w-100px h10 text-placeholder">实际通勤时长</text>
                        <text class="flex-1 h10" :class="{ 'text-danger': info.timeout, 'text-primary': !info.timeout }">{{
                            $func.getTimeText(info.commuting_time) }}</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">实际抵达时间</text>
                        <text class="flex-1 h10">{{ info.arrival_time }}</text>
                    </view>
                    <view class="flex flex-y-center" v-if="info.time > 0 && info.state === 4">
                        <text class="w-100px h10 text-placeholder">剩余 服务时长</text>
                        <x-countdown class="h1 text-primary" :time="info.time" @end="getDetails" />
                    </view>
                </view>
                <view class="flex grid-gap-4" v-if="info.state === 4">
                    <button class="flex-1 btn-primary btn-round" @tap="getTechnicianAppointmentService">加钟</button>
                    <button class="btn-danger-light-2 btn-round" @tap="endServiceModal">结束服务</button>
                </view>
            </view>

            <!-- 预约项目 -->
            <view class="p-4 rounded-4 bg-white flex flex-column grid-gap-4">
                <view class="flex flex-y-center grid-gap-2">
                    <text class="bg-primary-light-3 rounded-4" style="height: 8px;width: 8px;"></text>
                    <text class="h9 font-weight-600">预约项目</text>
                </view>
                <view class="flex flex-column grid-gap-4 bg">
                    <view class="bg-white py-2">
                        <x-project-item :project="info">
                            <template #action>
                                <view @tap.stop class="flex flex-center grid-gap-1">
                                    <text class="text-placeholder">x</text>
                                    <text class="font-weight-600 text-grey" v-if="info.num > 0">{{ info.num }}</text>
                                </view>
                            </template>
                        </x-project-item>
                    </view>
                </view>
            </view>
            <!-- 加钟详情 -->

            <view class="p-4 rounded-4 bg-white flex flex-column grid-gap-4" v-if="info.sub_orders && info.sub_orders.length">
                <view class="flex flex-y-center grid-gap-2">
                    <text class="bg-primary-light-3 rounded-4" style="height: 8px;width: 8px;"></text>
                    <text class="h9 font-weight-600">加钟记录</text>
                </view>

                <view class="flex flex-column grid-gap-3">
                    <view v-for="(item, index) in info.sub_orders" :key="index" class="overtime-item flex flex-column p-4 rounded-4" :class="{ 'overtime-unpaid': item.state === 0 }">
                        <view class="mb-3">
                            <text class="h10 text-placeholder">订单号：</text>
                            <text class="h10">{{ item.trade }}</text>
                        </view>

                        <view class="flex flex-x-space-between mb-3">
                            <text class="font-weight-600 h8">{{ item.title }}</text>
                            <text class="text-primary font-weight-600 h7">¥{{ item.price }}</text>
                        </view>

                        <view class="flex flex-x-space-between mb-2">
                            <view class="flex grid-gap-2 flex-y-center">
                                <text class="text-placeholder h10">时长</text>
                                <text class="h9">{{ item.service_duration }}分钟</text>
                            </view>
                            <view class="flex grid-gap-2 flex-y-center">
                                <text class="text-placeholder h10">状态</text>
                                <view class="status-tag" :class="{
                                    'status-unpaid': item.state === 0,
                                    'status-completed': item.state === 4
                                }">
                                    {{ item.state === 0 ? '未支付' : '已支付' }}
                                </view>
                            </view>
                        </view>

                        <view class="border-top pt-2">
                            <text class="text-placeholder h10">{{ item.create_time }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 订单详情 -->
            <view class="p-4 rounded-4 bg-white flex flex-column grid-gap-4">
                <view class="flex flex-y-center grid-gap-2">
                    <text class="bg-primary-light-3 rounded-4" style="height: 8px;width: 8px;"></text>
                    <text class="h9 font-weight-600">订单信息</text>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="h9 text-grey">{{ WebConfigStore.replaceIndustryPersonnelName('服务技师') }}</text>
                    <view class="flex flex-center grid-gap-1">
                        <image :src="info.technician_headimg" mode="scaleToFill" class="rounded-circle" style="width: 20px;height: 20px;" />
                        <text class="h10 text-primary font-weight-600">{{ info.technician_nickname }}</text>
                    </view>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">电话</text>
                    <text class="h10 text-primary font-weight-600" hover-class="bg" selectable user-select @tap="$api.AppointmentService.makePhoneCall({ id: info.id, action: 'user' })">{{ info.technician_mobile }}</text>
                </view>
                <view v-if="info.to_shop && info.shop_id" class="flex flex-column grid-gap-4">
                    <view class="flex flex-y-center flex-x-space-between">
                        <text class="text-grey h9">服务门店</text>
                        <text class="h10 text-dark font-weight-600" @tap="$page.open('/pages/mch/details?id=' + info.shop_id)">{{ info.shop_title
							}}</text>
                    </view>
                    <view class="flex flex-y-center">
                        <text class="text-grey h9">门店地址</text>
                        <view class="flex-1 flex flex-x-flex-end flex-y-center" @tap="openLocation">
                            <text class="h10 text-dark font-weight-600">
                                {{ info.shop_province }}
                                {{ info.shop_city }}
                                {{ info.shop_area }}
                                {{ info.shop_street }}
                                {{ info.shop_address }}
                            </text>
                            <image src="/static/icons/map-icon.png" mode="aspectFit" class="x-navbar-icons-image" style="width: 20px; height: 20px;" v-if="info.shop_longitude && info.shop_latitude" />
                        </view>
                    </view>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">订单编号</text>
                    <text class="h10 text-dark font-weight-600" hover-class="bg" selectable user-select>{{ info.trade
						}}</text>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">预约时间</text>
                    <text class="h10 text-dark font-weight-600" hover-class="bg" selectable user-select>{{
                        info.start_time }}</text>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">订单备注</text>
                    <text class="h10 text-dark font-weight-600">{{ info.remark }}</text>
                </view>
            </view>
        </view>
        <x-loading v-if="loading" />
        <overtime v-model:show="overtimeShow" :projects="projects" :remaining_minutes="remaining_minutes" :appointment_service_id="search.id" @update="getDetails" />
    </view>
</template>

<script setup lang="ts">
import overtime from './modules/overtime'; // 延长服务
import { ref, watch } from "vue";
import { onLoad, onPageScroll } from "@dcloudio/uni-app";
import { $api, $func, $message, $page } from "@/utils";
import { usePlatformStore, useWebConfigStore, useRefs } from "@/stores";
const PlatformStore = usePlatformStore();
const { PLATFORM } = useRefs(PlatformStore);
const WebConfigStore = useWebConfigStore();
const opacity = ref<{
    navbar: number | string
}>({
    navbar: 0,
});
const top = ref(0);
watch(() => top.value, (val: number) => {
    if (val < -10) {
        return;
    }
    opacity.value.navbar = val > 50 ? 1 : (val / 50).toFixed(1);
})

const loading = ref(false);
const overtimeShow = ref(false);
const remaining_minutes = ref(0);
const search = ref({
    id: '',
    action: 'user'
});
const info = ref({});
const projects = ref([]);
const getDetails = () => {
    loading.value = true
    $api.AppointmentService.details(search.value).then((data: any) => {
        console.log('技师当前服务全部时间', data);
        info.value = data
        if (data.arrival_time) {
            const arrival_time = new Date(data.arrival_time.replace(/-/g, '/'));
            const plan_arrival_time = new Date(data.start_time.replace(/-/g, '/'));
            plan_arrival_time.setMinutes(plan_arrival_time.getMinutes() + data.commuting_duration);
            info.value.plan_arrival_time = `${$func.getDayName(plan_arrival_time)} ${plan_arrival_time.getHours().toString().padStart(2, '0')}:${plan_arrival_time.getMinutes().toString().padStart(2, '0')}`;
            info.value.timeout = false;
            if (arrival_time > plan_arrival_time) {
                info.value.timeout = true;
            }
        }
        if (data.state === 4) {
            const service_start_time = new Date(data.service_start_time.replace(/-/g, '/'));
            service_start_time.setMinutes(service_start_time.getMinutes() + data.duration);
            const now = new Date;
            info.value.time = (service_start_time.getTime() - now.getTime()) / 1000;
        }
    }).catch(() => {
    }).finally(() => {
        loading.value = false
    })
}
const endService = () => {
    loading.value = true
    $api.AppointmentService.endService(search.value).then(() => {
        getDetails()
    }).catch((err: any) => {
        loading.value = false;
        $message.error(err.msg);
    })
}
const endServiceModal = () => {
    if (info.value.state === 4) {
        const service_start_time = new Date(info.value.service_start_time.replace(/-/g, '/'));
        service_start_time.setMinutes(service_start_time.getMinutes() + info.value.duration);
        const now = new Date;
        info.value.time = (service_start_time.getTime() - now.getTime()) / 1000;
        if (info.value.time > 0) {
            uni.showModal({
                title: '提示',
                content: '当前服务时间还未结束，是否确认提前结束服务？如有加钟需要退款，请先申请退款在结束服务。',
                success: (res) => {
                    if (res.confirm) {
                        endService();
                    }
                }
            })
        } else {
            endService();
        }
    }
}
const getTechnicianAppointmentService = () => {
    loading.value = true
    $api.AppointmentService.getTechnicianAppointmentService(search.value).then((res: any) => {
        console.log('getTechnicianAppointmentService', res)
        overtimeShow.value = true;
        remaining_minutes.value = res.remaining_minutes;
        projects.value = res.projects
    }).catch((err: any) => {
        $message.error(err.msg);
    }).finally(() => {
        loading.value = false
    })
}
const openLocation = () => {
    if (!info.value.shop_longitude || !info.value.shop_latitude) {
        return;
    }
    uni.openLocation({
        latitude: info.value.shop_latitude,
        longitude: info.value.shop_longitude,
        name: info.value.shop_title,
        address: `${info.value.shop_province}${info.value.shop_city}${info.value.shop_area}${info.value.shop_street}${info.value.shop_address}`
    });
}
onPageScroll(({ scrollTop }: { scrollTop: number }) => {
    top.value = scrollTop;
})
onLoad((options: any) => {
    search.value.id = options.id;
    getDetails();
});
</script>

<style lang="scss">

    /* #ifdef H5 */
    uni-page[data-page="pages/user/service/details"] {

        /* #endif */
        page {
            background: radial-gradient(circle at 15% 20%, var(--xl-primary) -100%, transparent 35%),
                radial-gradient(circle at 27% 5%, var(--xl-primary-light-3) -50%, transparent 30%),
                radial-gradient(circle at 85% 17%, var(--xl-primary-light-1) -50%, transparent 25%);
            background-repeat: no-repeat;
            background-position: top center;
            background-color: $uni-bg-color-grey;
            /* #ifdef H5 */
            background-attachment: fixed;
            /* #endif */
        }

        /* #ifdef H5 */
    }

    /* #endif */
</style>
<style lang="scss" scoped>
    .w-100px {
        width: 100px;
    }

    .state-icon {
        width: min(10.6667vw, 40px);
        height: min(10.6667vw, 40px);
    }

    .state-text {
        font-size: min(14px, 3.2vw);
    }

    .overtime-item {
        background: rgba(var(--xl-primary-rgb), 0.05);
        border: 1px solid rgba(var(--xl-primary-rgb), 0.1);

        &.overtime-unpaid {
            background: rgba(var(--xl-danger-rgb), 0.05);
            border: 1px solid rgba(var(--xl-danger-rgb), 0.1);
        }
    }

    .mt-2 {
        margin-top: 8px;
    }
</style>
